# -*- coding: utf-8 -*-
import csv
from py2neo import Graph, Node, Relationship, NodeMatcher
from config.database import DatabaseConfig

# 从配置文件获取数据库配置
db_config = DatabaseConfig.get_neo4j_config()
g = Graph(db_config["uri"], auth=db_config["auth"])

def create_relations():
    matcher = NodeMatcher(g)
    
    # 导入知识点前置关系
    with open('resource/data/课程知识图谱数据/关系/知识点-前置知识点-知识点.csv', 'r', encoding='ANSI') as f:
        reader = csv.reader(f)
        for item in reader:
            if reader.line_num == 1:
                continue
            print("当前关系：", reader.line_num, "当前内容", item)
            findnode = matcher.match('知识点', id=item[0]).first()
            endnode = matcher.match('知识点', id=item[1]).first()
            relationships = Relationship(findnode, '前置知识点', endnode)
            g.merge(relationships, "", "id")
    
    # 导入知识点后继关系
    with open('resource/data/课程知识图谱数据/关系/知识点-后继知识点-知识点.csv', 'r', encoding='ANSI') as f:
        reader = csv.reader(f)
        for item in reader:
            if reader.line_num == 1:
                continue
            print("当前行数：", reader.line_num, "当前内容", item)
            findnode = matcher.match('知识点', id=item[0]).first()
            endnode = matcher.match('知识点', id=item[1]).first()
            relationships = Relationship(findnode, '后继知识点', endnode)
            g.merge(relationships, "", "id")
    
    # 导入知识单元前置关系
    with open('resource/data/课程知识图谱数据/关系/知识单元-前置知识单元-知识单元.csv', 'r', encoding='ANSI') as f:
        reader = csv.reader(f)
        for item in reader:
            if reader.line_num == 1:
                continue
            print("当前行数：", reader.line_num, "当前内容", item)
            findnode = matcher.match('知识单元', id=item[0]).first()
            endnode = matcher.match('知识单元', id=item[1]).first()
            relationships = Relationship(findnode, '前置知识单元', endnode)
            g.merge(relationships, "", "id")
    
    # 导入知识单元后继关系
    with open('resource/data/课程知识图谱数据/关系/知识单元-后继知识单元-知识单元.csv', 'r', encoding='ANSI') as f:
        reader = csv.reader(f)
        for item in reader:
            if reader.line_num == 1:
                continue
            print("当前行数：", reader.line_num, "当前内容", item)
            findnode = matcher.match('知识单元', id=item[0]).first()
            endnode = matcher.match('知识单元', id=item[1]).first()
            relationships = Relationship(findnode, '后继知识单元', endnode)
            g.merge(relationships, "", "id")

if __name__ == '__main__':
    create_relations() 